package com.zywl.service.impl;

import com.zywl.core.beans.AssResRel;
import com.zywl.core.beans.Association;
import com.zywl.core.beans.User;
import com.zywl.core.dao.mapper.sys.AssResRelMapper;
import com.zywl.core.dao.mapper.sys.AssociationMapper;
import com.zywl.core.dao.mapper.sys.UserMapper;
import com.zywl.service.AssociationService;
import com.zywl.service.impl.base.BaseServiceImpl;
import com.zywl.utils.utils.Constants;
import com.zywl.utils.utils.GenerateCodeUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class AssociationServiceImpl extends BaseServiceImpl<AssociationMapper, Association> implements AssociationService {
    @Autowired
    private AssResRelMapper relMapper;
    @Autowired
    private UserMapper userMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(Association t, String ids) throws Exception {
        mapper.insert(t);
        //添加协会的同时添加登入用户
        if(StringUtils.isNotEmpty(t.getAssPrincipalMobile())){
            User user = new User();
            user.setUsrUsername(t.getAssPrincipalMobile());
            user.setUsrPassword(GenerateCodeUtil.MD5("123456"));
            user.setUsrName(t.getAssPrincipal());
            user.setUsrAssociationId(t.getAssId());
            user.setUsrMobile(t.getAssPrincipalMobile());
            user.setUsrStt("0");
            user.setUsrCreateTime(t.getAssCreateTime());
            user.setUsrModifyTime(t.getAssCreateTime());
            userMapper.insert(user);
        }

        if (StringUtils.isNotEmpty(ids)) {
            String[] id_s = ids.split(Constants.STRING_SPLIT);
            AssResRel rel = null;
            for (String id : id_s) {
                rel = new AssResRel();
                rel.setArsAssId(t.getAssId());
                rel.setArsResId(Long.parseLong(id));
                relMapper.insert(rel);
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void update(Association t, String ids) throws Exception {
        mapper.updateByPrimaryKey(t);
        relMapper.deleteByAssId(t.getAssId());
        if (StringUtils.isNotEmpty(ids)) {
            String[] id_s = ids.split(Constants.STRING_SPLIT);
            AssResRel rel = null;
            for (String id : id_s) {
                rel = new AssResRel();
                rel.setArsAssId(t.getAssId());
                rel.setArsResId(Long.parseLong(id));
                relMapper.insert(rel);
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteById(Long id) throws Exception {
        mapper.deleteByPrimaryKey(id);
        relMapper.deleteByAssId(id);
    }

}
